package com.business.action.system;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.business.bean.system.FileBean;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import net.sf.rose.file.util.FileUtils;
import net.sf.rose.jdbc.PageBean;
import net.sf.rose.util.StringUtil;
import net.sf.rose.web.util.WebUtils;
import sun.misc.BASE64Encoder;

/**
 * @author: fengjian
 * @date: 2018/06/28 22:30
 * @description:图片文件的上传与下载
 */
@RestController
@RequestMapping("file")
public class FileAction {

    private Logger logger = LoggerFactory.getLogger(getClass());

	/**
	 * 控件上传图片
	 * @return
	 */
	@RequestMapping("upload.do")
	public PageBean upload(HttpServletRequest request) {
		PageBean page = new PageBean();
		FileBean fb = null;
		List<FileBean> list = WebUtils.saveImage(request);
		if (list.size() > 0) {
			fb = list.get(0);
		}
		page.setData(fb);
		return page;
	}

	/**
	 * 获取图片文件64位编码
	 * @param url
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/any/getFile.do")
	public PageBean getFile(HttpServletResponse response, String url) {
		PageBean page = new PageBean();
		File path = FileUtils.IMAGE_PATH;
		File file = new File(path, url);
		if (!file.exists()) {
			page.setSuccess(false);
			System.out.println(file.getAbsolutePath() + "文件没有找到...");
			page.setMessage(file.getAbsolutePath() + "文件没有找到...");
			return page;
		}
		String filename = file.getName();
		try {
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(file));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
		} catch (Exception e) {
			logger.error("获取图片文件时发生错误！", e);
			page.setSuccess(false);
			page.setMessage(e.getMessage());
		}
		return page;
	}

	/**
	 * 获取图片文件64位编码
	 * @param url
	 * @return
	 */
	@RequestMapping("getImg.do")
	public String getImg(String url) {
		File path = FileUtils.IMAGE_PATH;
		path = new File(path, url);
		String imgStr = "";
		try {
			byte[] img_data = null;
			// 读取图片字节数组
			InputStream in = new FileInputStream(path);
			img_data = new byte[in.available()];
			in.read(img_data);
			in.close();
			// 对字节数组Base64编码
			BASE64Encoder encoder = new BASE64Encoder();
			imgStr = encoder.encode(img_data);
		} catch (Exception e) {
			logger.error("获取图片文件时发生错误！", e);
		}
		return imgStr;
	}

	/**
	 * ueditor控件上传图片
	 * @param url
	 * @return
	 */
	//@RequestMapping("ueditor/upload.do")
	public String ueditorUpload(HttpServletRequest request) {
		List<FileBean> list = WebUtils.saveImage(request);
		FileBean fb = list.get(0);
		StringBuilder builder = new StringBuilder();
		builder.append( "{" );
		builder.append( "\"state\": \"SUCCESS\"" );
		builder.append( ",\"original\": \"" + fb.getOriginalName() +"\"" );
		builder.append( ",\"size\": \"" + fb.getSize() +"\"" );
		builder.append( ",\"type\": \"" + fb.getType() +"\"" );
		builder.append( ",\"url\": \"" + fb.getUrl() +"\"" );
		builder.append( ",\"title\": \"" + fb.getFileName() +"\"" );
		builder.append( "}" );
		return StringUtil.toUnicode(builder.toString());
	}
}